<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="100px">
      <el-form-item prop="employeeName">
        <el-input v-model="queryParams.employeeName" :placeholder="$t('employee_name1')" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item prop="employerId">
        <employerSelect v-model="queryParams.employerId"></employerSelect>
      </el-form-item>
      <el-form-item prop="department">
        <treeselect :normalizer="normalizer" v-model="queryParams.department" :options="deptOptions" :show-count="true"
          :placeholder="$t('all_departments')" style="width: 200px" :disabled="queryParams.employerId == null" />
      </el-form-item>
      <el-form-item prop="operationalType">
        <el-select v-model="queryParams.operationalType" :placeholder="$t('calculation_type')" clearable>
          <el-option v-for="dict in dict.type.salary_calculation_type" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">{{ $t("search") }}</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">{{
          $t("reset")
        }}</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" style="margin-top: 20px">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAddPayGroup">{{
          $t("add_new_payroll_item") }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-plus" size="mini" :disabled="queryParams.employerId == null"
          @click="handleAddEmployee">{{ $t("add_new_employee") }}</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-bottom"
          size="mini"
          @click="handleExport"
          >{{ $t("download_template") }}</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-top"
          size="mini"
          @click="handleImport"
          >{{ $t("import_payroll_data") }}</el-button
        >
      </el-col> -->
    </el-row>

    <el-table style="margin-top: 10px" v-loading="loading" :data="tableList" border :max-height="tableHeight">
      <el-table-column :label="item.title" align="center" v-for="(item, index) in tableColumn" :key="index"
        :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <div v-for="(listItem, listIndex) in tableList[scope.$index].dataList" :key="listIndex">
            <span v-if="index == listIndex">
              <template v-if="Object.prototype.toString.call(listItem) === '[object Object]'
                ">
                {{  listItem.projectDataSourceValue }}
              </template>
              <template v-else>
                {{ listItem }}
              </template>
            </span>
          </div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('action')" align="center" class-name="small-padding fixed-width" width="160"
        fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">{{ $t("modify")
          }}</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">{{ $t("delete")
          }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" 
      :page-sizes="[10,20,30,50,100, 200]"
      />

    <div style="text-align: center; margin-top: 60px">
      <el-button type="primary" plain @click="preStep">{{
        $t("previous")
      }}</el-button>
      <el-button type="primary" @click="nextStep">{{ $t("next") }}</el-button>
    </div>

    <!-- 添加或修改薪酬运算列表对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="160px">
        <el-form-item :label="item.title" v-for="(item, index) in tableColumn" :key="index">
          <template v-if="Object.prototype.toString.call(form.dataList[index]) ===
            '[object Object]'
            ">
            <salaryProjectEdit :itemForm.sync="form.dataList[index]"></salaryProjectEdit>
          </template>
          <el-input v-model="form.dataList[index]" placeholder="" disabled v-else />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{
          $t("confirm")
        }}</el-button>
        <el-button @click="cancel">{{ $t("cancel") }}</el-button>
      </div>
    </el-dialog>

    <!-- 导入弹窗 -->
    <importModal ref="importModal" :title="$t('import')" downloadUrl="" uploadUrl=""
      :downloadName="$t('download_template')" @refreshList="getList"></importModal>

    <!-- 选择雇员 -->
    <employeeModal ref="employeeModal" :salaryCalculationId="salaryCalculationForm.id"
      :employerId="queryParams.employerId" @handleCheck="checkEmployee"></employeeModal>
    <!-- 选择薪酬组 -->
    <salaryProjectModal ref="salaryProjectModal" @handleCheck="checkSalaryProject"></salaryProjectModal>
  </div>
</template>

<script>
import {
  getSalaryCalculationEmpList,
  addSalaryCalculationEmp,
  addSalaryCalculationProject,
  removeEmp,
  updateAmountAdjustment,
} from "@/api/salary/salaryCalculation";
import { deptTreeSelect } from "@/api/system/user";
import salaryProjectEdit from "../salaryProjectEdit.vue";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import employerSelect from "@/views/components/custom/employerSelect.vue";
import importModal from "@/views/components/custom/importModal.vue";
import employeeModal from "./employeeModal.vue";
import salaryProjectModal from "./salaryProjectModal.vue";
export default {
  components: {
    Treeselect,
    employerSelect,
    importModal,
    employeeModal,
    salaryProjectModal,
    salaryProjectEdit,
  },
  props: {
    salaryCalculationForm: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  dicts: ["salary_calculation_type"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        employeeName: null,
        employerId: null,
        department: null,
        operationalType: null,
      },
      tableColumn: [],
      tableList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      form: {
        dataList: [],
      },
      rules: {},
      deptOptions: [],
    };
  },
  created() {
    this.getList();
  },
  watch: {
    "queryParams.employerId": {
      handler(val) {
        if (val) {
          this.getDeptTree();
        } else {
          this.deptOptions = [];
        }
        this.queryParams.department = null;
      },
      immediate: true,
    },
  },
  methods: {
    getList() {
      getSalaryCalculationEmpList({
        ...this.queryParams,
        salaryCalculationId: this.salaryCalculationForm.id,
      }).then((res) => {
        this.tableColumn = res.data.headerList.map((item) => {
          return {
            title: item,
          };
        });
        let list = JSON.parse(JSON.stringify(res.data.empInfoList))
        // 剔除不需要展示的项
        list.forEach((item) => {
          var flag = item.dataList.findIndex(item => {
            return item === '============';
          })
          item.dataList.splice(flag,1)
        });
        this.tableList = list;
        this.loading = false;
      });
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect(this.queryParams.employerId).then((response) => {
        this.deptOptions = response.data;
      });
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.deptName,
        children: node.children || [],
      };
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 添加薪酬项目 */
    handleAddPayGroup() {
      this.$refs.salaryProjectModal.showModal();
    },
    checkSalaryProject(row) {
      addSalaryCalculationProject({
        salaryProjectId: row.id,
        salaryCalculationId: this.salaryCalculationForm.id,
        isShowPaySheet: row.isShowPaySheet,
        isShowSalaryReport: row.isShowSalaryReport,
      }).then((res) => {
        this.$modal.msgSuccess(this.$t("operation_successful"));
        this.$refs.salaryProjectModal.closeModal();
        this.getList();
      });
    },
    /** 添加雇员 */
    handleAddEmployee() {
      this.$refs.employeeModal.showModal();
    },
    checkEmployee(row) {
      addSalaryCalculationEmp({
        empId: row.id,
        salaryCalculationId: this.salaryCalculationForm.id,
      }).then((res) => {
        this.$modal.msgSuccess(this.$t("operation_successful"));
        this.$refs.employeeModal.closeModal();
        this.getList();
      });
    },
    /** 导出 */
    handleExport() {
      this.download(
        "salary/salaryCalculation/downloadTemplate.do",
        {},
        `salaryCalculation_${new Date().getTime()}.xlsx`
      );
    },
    /** 导入 */
    handleImport() {
      this.$refs.importModal.showModal();
    },
    /** 修改 */
    handleUpdate(row) {
      this.title = this.$t("modify");
      this.open = true;
      this.form = { ...row };
    },
    /** 删除 */
    handleDelete(row) {
      this.$modal
        .confirm(this.$t("delete_data"))
        .then(function () {
          return removeEmp(row.salaryCalculationEmpId);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess(this.$t("operation_successful"));
        })
        .catch(() => { });
    },
    cancel() {
      this.open = false;
    },
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let list = this.form.dataList.filter((item) => {
            return Object.prototype.toString.call(item) === "[object Object]";
          });
          updateAmountAdjustment({
            salaryCalculationId: this.salaryCalculationForm.id,
            salaryCalculationEmpId: this.form.salaryCalculationEmpId,
            empProjectResultList: list,
          }).then((response) => {
            this.$modal.msgSuccess(this.$t("operation_successful"));
            this.open = false;
            this.getList();
          });
        }
      });
    },

    preStep() {
      this.$emit("changeStep", 1);
    },
    nextStep() {
      this.$emit("changeStatus", 2);
    },
  },
};
</script>
<style scoped lang="scss"></style>
